package cn.com.gridinfo.sooc.core.expand.callname.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.expand.callname.adapter.StudentMenuAdapter;
import cn.com.gridinfo.sooc.core.expand.callname.bean.Student;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 学生名单界面
 *
 * @author yingchunli
 */
public class StudentMenuActivity extends BaseSoocActivity {

    @InjectView(R.id.toolbar_rightbtn)
    ImageView toolbarRightIcon;//toolbar右侧的图标
    @InjectView(R.id.kcmc_studentmenu)
    TextView kcmc;//课程名称
    @InjectView(R.id.skxq_studentmenu)
    TextView skxq;//上课学期
    @InjectView(R.id.count_studentmenu)
    TextView countMenu;//名单人数
    @InjectView(R.id.searchcontent)
    ClearEditText search_content;//搜索的内容
    @InjectView(R.id.list_studentmenu)
    UltimateRecyclerView listStudentmenu;//学生名单列表
    LinearLayoutManager linearLayoutManager;//布局管理器
    StudentMenuAdapter adapter;//适配器
    CallNameDao dao;
    String kcid;//课程id
    private final int INTENT_ADDSTUDNET = 10;//跳转到添加学生界面的常量
    int maxLastPositon;//数据最后位置
    int delPosition;//要删除的学生
    @InjectView(R.id.url_load)
    TextView url_blank;//空白页提示的url
    @InjectView(R.id.tip_feedback)
    TextView tip_search;//搜索为空时，空白页提示
    @InjectView(R.id.tip_studentmenu)
    LinearLayout tip_blank;//空白页提示，没搜索时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expand_studentmenu);
        ButterKnife.inject(this);
        dao = new CallNameDao(this);

        //空白页的提示
        url_blank.setText(Arad.preferences.getString(LocalMark.SERVER_URL.getName()) + "上传名单。");

        //初始化listView
        linearLayoutManager = new LinearLayoutManager(this);
        listStudentmenu.setLayoutManager(linearLayoutManager);
        //设置toolbar的右侧添加学生图标
        toolbarRightIcon.setImageResource(R.mipmap.expand_add_student_icon);
        //给顶部的课程名称  上课学期  赋值
        kcmc.setText(getIntent().getStringExtra("kcmc"));
        skxq.setText(getIntent().getStringExtra("skxq"));
        kcid = getIntent().getStringExtra("kcid");
        initView();
        //发送请求  获取列表数据
        PageConst.pageNo = 1;
        PageConst.pageSize = 20;
        dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);


        //按键监听
        search_content.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        search_content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearchClick();
                }
                return false;
            }
        });
    }

    /**
     * 初始化界面数据
     */
    private void initView() {
        List<Student> studentList = new ArrayList<>();
        adapter = new StudentMenuAdapter(studentList, this);//初始化适配器
        listStudentmenu.setAdapter(adapter);//设置适配器
        listStudentmenu.enableLoadmore();
        //下拉刷新数据
        listStudentmenu.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                PageConst.pageNo = 1;//首页
                if (search_content.getText().toString().trim() != null) {
                    dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, search_content.getText().toString().trim(), CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
                } else {
                    dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
                }
                linearLayoutManager.scrollToPosition(0);
            }
        });
        //加载更多数据
        listStudentmenu.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
//                if (itemsCount > (PageConst.pageSize - 1)) {
//                    maxLastPositon = maxLastVisiblePosition;
//                    if (search_content.getText().toString().trim() != null) {
//                        dao.getStudentList(kcid, ++PageConst.pageNo, PageConst.pageSize, search_content.getText().toString().trim(), CodeConst.EXPAND_GET_STUDENTMENU_PULLUP);
//                    } else {
//                        dao.getStudentList(kcid, ++PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PULLUP);
//                    }
//                } else {
//                    adapter.loadNoDataView();
//                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
//                }
            }
        });
        //适配器的单项点击事件
        adapter.setmOnItemClickLitener(new StudentMenuAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, final Student student, int position) {

                Log.d("kcid->" + kcid);
                Log.d("xh->" + student.getXh());
                delPosition = position;

                new MaterialDialog.Builder(StudentMenuActivity.this)
                        .items(R.array.del_studnet)
                        .backgroundColor(getResources().getColor(R.color.white))
                        .contentColor(getResources().getColor(R.color.color_tv333))
                        .contentGravity(GravityEnum.CENTER)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                //删除学生
                                Log.d("删除学生");
                                dao.deleteStudent(kcid, student.getXh(), CodeConst.EXPAND_DEL_STUDENT);
                            }
                        })
                        .show();

            }
        });
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.getStatus().equals("0")) {
                switch (requestCode) {
//                    case CodeConst.EXPAND_GET_STUDENTMENU_FRIST:
//                        //获取学生名单列表数据    首次请求
//                        initView();
//                        break;
                    case CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN:
                        //下拉请求，刷新数据
                        listStudentmenu.setRefreshing(false);
                        if (dao.getStudentList() != null && !dao.getStudentList().isEmpty()) {
                            listStudentmenu.hideEmptyView();
                            countMenu.setText(dao.getMdrs() + "");//设置名单总人数
                            adapter.refresh(dao.getStudentList());
                            adapter.loadNoDataView();
                        } else {
                            //无数据处理
                            countMenu.setText("0");//设置名单总人数

                            if (search_content.getText().toString().trim().equals("")) {
                                //没有搜索时，空白页设置
                                tip_search.setVisibility(View.GONE);
                                tip_blank.setVisibility(View.VISIBLE);
                            } else {
                                tip_search.setText("没有找到相关名单");
                                tip_search.setVisibility(View.VISIBLE);
                                tip_blank.setVisibility(View.GONE);
                            }
                            listStudentmenu.showEmptyView();
                        }
                        break;
                    case CodeConst.EXPAND_GET_STUDENTMENU_PULLUP://获取列表数据  上拉请求
                        //获取列表数据  下拉请求
                        if (dao.getStudentList() != null && !dao.getStudentList().isEmpty()) {
                            adapter.loadmore(dao.getStudentList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                    case CodeConst.EXPAND_DEL_STUDENT:
                        //删除学生成功
                        MessageUtils.showRightImageShortToast(this, "删除学生成功");
                        adapter.delete(delPosition);//列表中删除本条数据
                        int mdrs = Integer.parseInt(countMenu.getText().toString().trim());
                        countMenu.setText(mdrs - 1 + "");//设置名单总人数
                        if (adapter.getIsLoadMore()) {
                            if (adapter.getAdapterItemCount() < PageConst.pageSize) {
                                //下拉刷新  账户明细数据
                                PageConst.pageNo = 1;//首页
                                if (search_content.getText().toString().trim() != null) {
                                    dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, search_content.getText().toString().trim(), CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
                                } else {
                                    dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
                                }
                                linearLayoutManager.scrollToPosition(0);
                            }
                        }

                        break;
                }
            } else {
                MessageUtils.showImageShortToast(this, dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(this, "请求数据异常");
        }
    }

    /**
     * 搜索按钮的点击
     */
    @OnClick(R.id.search_studentmenu)
    void onSearchClick() {
        //搜索学生
        if (!search_content.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            PageConst.pageSize = 20;
            dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, search_content.getText().toString().trim(), CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
        }
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(search_content.getWindowToken(), 0);
    }

    /**
     * 判断搜索内容，是否为空，否，搜索全部内容
     */
    @OnTextChanged(value = {R.id.searchcontent}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (search_content.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK != resultCode) return;
        switch (requestCode) {
            case INTENT_ADDSTUDNET://从添加学生界面返回
                //刷新列表
                PageConst.pageNo = 1;
                dao.getStudentList(kcid, PageConst.pageNo, PageConst.pageSize, null, CodeConst.EXPAND_GET_STUDENTMENU_PUSHDOWN);
                break;
        }
    }

    @Override
    public String setupToolBarTitle() {
        return "学生名单";
    }

    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    @Override
    public boolean setupToolBarRightButton(ImageView rightButton) {
        return true;
    }

    @OnClick(R.id.toolbar_leftbtn)
    void onToolbarLeft() {
        setResult(RESULT_OK);
        finish();
    }

    /**
     * 添加学生
     */
    @OnClick(R.id.toolbar_rightbtn)
    void onToolbarRight() {
        //跳转到添加学生页面
        Intent intent = new Intent(this, AddStudentActivity.class);
        intent.putExtra("kcid", kcid);
        startActivityForResult(intent, INTENT_ADDSTUDNET);
        AnimUtil.intentSlidIn(this);
    }
}
